<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

// +----------------------------------------------------------------------
// | 自动执行  每分钟执行一次 crontab -e 加入 */1 * * * * curl https://域名/?s=/ApiAuto/index/key/配置文件中的authtoken
// +----------------------------------------------------------------------
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Log;
class ApiAuto extends BaseController
{
    public function initialize(){

	}
	public function index(){
		$config = include(ROOT_PATH.'config.php');
		set_time_limit(0);
		ini_set('memory_limit', -1);
		if(input('param.key')!=$config['authtoken']) die('error');
		$this->perminute();
		//执行了多少次了
		$lastautotimes = cache('autotimes');
		if(!$lastautotimes) $lastautotimes = 0;
		cache('autotimes',$lastautotimes+1);

		//Log::write('perminute');
		$lastautohour = cache('autotimehour');
		if(!$lastautohour){
			$lastautohour = strtotime(date("Ymd H:00:00")); //整点执行
			cache('autotimehour',$lastautohour);
		}
		if($lastautohour <= time() - 3600){
			cache('autotimehour',time());
			$this->perhour();
			//Log::write('perhour');
		}
		$lastautoday = cache('autotimeday');
		if(!$lastautoday){
			$lastautoday = strtotime(date("Ymd 06:00:00")); //6点执行
			cache('autotimeday',$lastautoday);
		}
		if($lastautoday <= time() - 86400){
			cache('autotimeday',time());
			$this->perday();
			\think\facade\Log::write('perday');
		}

		if(getcustom('plug_yuebao')){

			//定时0点执行
			$time = (int)date("H",time());
			if($time == 0){

				//确保一天执行一次
				$yuebaotime = cache('yuebaotime');

				$n_time = strtotime(date("Y-m-d",time()));

				if(!$yuebaotime){
					cache('yuebaotime',$n_time);
				}else{
					if($yuebaotime == $n_time){
						return;
					}else{
						cache('yuebaotime',$n_time);
					}
				}

				//计算余额宝收益
				$this->yuebao();

			}
		}

		die;
	}
	//每分钟执行一次
	private function perminute(){

		$time = time();
		//60分钟自动关闭订单 释放库存
		$orderlist = Db::name('shop_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('shop_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('shop_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				$oglist = Db::name('shop_order_goods')->where('aid',$aid)->where('orderid',$orderid)->select()->toArray();
				foreach($oglist as $og){
					Db::name('shop_guige')->where('aid',$aid)->where('id',$og['ggid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
					Db::name('shop_product')->where('aid',$aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
					if(getcustom('guige_split')){
						\app\model\ShopProduct::addlinkstock($og['proid'],$og['ggid'],$og['num']);
					}
				}
				//优惠券抵扣的返还
				if($order['coupon_rid']){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id','in',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				$rs = Db::name('shop_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				Db::name('shop_order_goods')->where('orderid',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				//return $this->json(['status'=>1,'msg'=>'操作成功']);
				//$rs = \app\common\Wxpay::closeorder($order['aid'],$order['ordernum'],$order['platform']);
			}
		}
		//秒杀
		$orderlist = Db::name('seckill_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('seckill_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('seckill_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				Db::name('seckill_product')->where('aid',$aid)->where('id',$order['proid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
				//优惠券抵扣的返还
				if($order['coupon_rid'] > 0){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				$rs = Db::name('seckill_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			}
		}

		//积分兑换
		$orderlist = Db::name('scoreshop_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid']]){
				$autocloseArr[$order['aid']] = Db::name('scoreshop_sysset')->where('aid',$order['aid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);
			$order = Db::name('scoreshop_order')->where('id',$orderid)->find();
			if(!$order || $order['status']!=0){
				//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
			}else{
				//加库存
				$oglist = Db::name('scoreshop_order_goods')->where('aid',$aid)->where('orderid',$orderid)->select()->toArray();
				foreach($oglist as $og){
					Db::name('scoreshop_product')->where('aid',$aid)->where('id',$og['proid'])->update(['stock'=>Db::raw("stock+".$og['num']),'sales'=>Db::raw("IF(sales>=".$og['num'].",sales-".$og['num'].",0)")]);
				}
				//优惠券抵扣的返还
				if($order['coupon_rid'] > 0){
					Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
				}
				$rs = Db::name('scoreshop_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				Db::name('scoreshop_order_goods')->where('orderid',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			}
		}


		//预约服务
		$orderlist = Db::name('yuyue_order')->where('status',0)->select()->toArray();
		$autocloseArr = [];
		foreach($orderlist as $order){
			if(!$autocloseArr[$order['aid'].'_'.$order['bid']]){
				$autocloseArr[$order['aid'].'_'.$order['bid']] = Db::name('yuyue_set')->where('aid',$order['aid'])->where('bid',$order['bid'])->value('autoclose');
			}
			if($order['createtime'] + $autocloseArr[$order['aid'].'_'.$order['bid']]*60 > time()) continue;
			$aid = $order['aid'];
			$mid = $order['mid'];
			$orderid = intval($order['id']);

			//加库存
			Db::name('yuyue_product')->where('aid',$aid)->where('id',$order['proid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
			Db::name('yuyue_guige')->where('aid',$aid)->where('id',$order['ggid'])->update(['stock'=>Db::raw("stock+".$order['num']),'sales'=>Db::raw("IF(sales>=".$order['num'].",sales-".$order['num'].",0)")]);
			//优惠券抵扣的返还
			if($order['coupon_rid'] > 0){
				Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
			}
			$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
			//积分抵扣的返还
			if($order['scoredkscore'] > 0){
				\app\common\Member::addscore($aid,$order['mid'],$order['scoredkscore'],'订单退款返还');
			}
			//退款成功通知
			$tmplcontent = [];
			$tmplcontent['first'] = '您的订单已经完成退款，¥'.$order['refund_money'].'已经退回您的付款账户，请留意查收。';
			$tmplcontent['remark'] = '请点击查看详情~';
			$tmplcontent['orderProductPrice'] = (string) $order['refund_money'];
			$tmplcontent['orderProductName'] = $order['title'];
			$tmplcontent['orderName'] = $order['ordernum'];
			\app\common\Wechat::sendtmpl(aid,$order['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('pages/my/usercenter'));
			//订阅消息
			$tmplcontent = [];
			$tmplcontent['amount6'] = $order['refund_money'];
			$tmplcontent['thing3'] = $order['title'];
			$tmplcontent['character_string2'] = $order['ordernum'];
			
			$tmplcontentnew = [];
			$tmplcontentnew['amount3'] = $order['refund_money'];
			$tmplcontentnew['thing6'] = $order['title'];
			$tmplcontentnew['character_string4'] = $order['ordernum'];
			\app\common\Wechat::sendwxtmpl($aid,$order['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

			//短信通知
			$member = Db::name('member')->where('id',$order['mid'])->find();
			if($member['tel']){
				$tel = $member['tel'];
			}else{
				$tel = $order['tel'];
			}
			$rs = \app\common\Sms::send($aid,$tel,'tmpl_tuisuccess',['ordernum'=>$order['ordernum'],'money'=>$order['refund_money']]);
		}

		//预约服务 几分钟内未接单自动退款
		if(getcustom('hmy_yuyue')){
			$orderlist = Db::name('yuyue_order')->where('status',1)->where('worker_orderid',0)->select()->toArray();
			$autocloseArr = [];
			foreach($orderlist as $order){
				if(!$autocloseArr[$order['aid'].'_'.$order['bid']]){
					$autocloseArr[$order['aid'].'_'.$order['bid']] = Db::name('yuyue_set')->where('aid',$order['aid'])->where('bid',$order['bid'])->value('minminute');
				}
				if($order['paytime'] + $autocloseArr[$order['aid'].'_'.$order['bid']]*60 > time()) continue;
				$aid = $order['aid'];
				$mid = $order['mid'];
				$bid = $order['bid'];
				$orderid = intval($order['id']);
				//	$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				//退款
				Db::name('yuyue_order')->where('id',$orderid)->where('aid',$aid)->where('bid',$bid)->update(['status'=>4,'refund_status'=>2,'refund_money'=>$order['totalprice'],'refund_reason'=>'超时未接单退款','refund_time'=>time()]);
				$rs = \app\common\Order::refund($order,$order['totalprice'],'超时未接单退款');

				$config = include(ROOT_PATH.'config.php');
				$appId=$config['hmyyuyue']['appId'];
				$appSecret=$config['hmyyuyue']['appSecret'];
				$headrs = array('content-type: application/json;charset=UTF-8','appid:'.$appId,'appSecret:'.$appSecret);
				$url = 'https://shifu.api.kkgj123.cn/api/1/order/cancel';
				$data = [];
				$data['sysOrderNo'] = $order['sysOrderNo'];
				$data['cancelParty'] = 3;
				$data['cancelReason'] = '超时取消';
				$data = json_encode($data,JSON_UNESCAPED_UNICODE);
				$res = curl_post($url,$data,'',$headrs);
				$res = json_decode($res,true);
			}
		}
		//超时的团
		$time = time();
		$tlist = Db::name('collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->select()->toArray();
		Db::name('collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->update(['status'=>3]);//改成失败状态
		if($tlist){//退款
			foreach($tlist as $t){
				$sysset = Db::name('admin')->where('id',$t['aid'])->find();
				$orderlist = Db::name('collage_order')->where('status',1)->where('teamid',$t['id'])->where('buytype','<>',1)->select()->toArray();
				foreach($orderlist as $orderinfo){
					if($orderinfo['paytype']=='微信支付'){
						$rs = \app\common\Wxpay::refund($orderinfo['aid'],$orderinfo['platform'],$orderinfo['ordernum'],$orderinfo['totalprice'],$orderinfo['totalprice'],'拼团失败');
					}else{
						\app\common\Member::addmoney($orderinfo['aid'],$orderinfo['mid'],$orderinfo['totalprice'],'拼团失败退款');
					}
					//积分抵扣的返还
					if($orderinfo['scoredk'] > 0){
						\app\common\Member::addscore($orderinfo['aid'],$orderinfo['mid'],$orderinfo['scoredk'],'拼团失败退款返还');
					}
					//优惠券抵扣的返还
					if($orderinfo['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',aid)->where('mid',$orderinfo['mid'])->where('id',$orderinfo['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					Db::name('collage_order')->where('id',$orderinfo['id'])->update(['status'=>4]);
					//退款成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '拼团失败退款，¥'.$orderinfo['totalprice'].'已经退回您的付款账户，请留意查收。';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['orderProductPrice'] = (string) $orderinfo['totalprice'];
					$tmplcontent['orderProductName'] = $orderinfo['title'];
					$tmplcontent['orderName'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('activity/collage/orderlist',$orderinfo['aid']));
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount6'] = $orderinfo['totalprice'];
					$tmplcontent['thing3'] = $orderinfo['title'];
					$tmplcontent['character_string2'] = $orderinfo['ordernum'];
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $orderinfo['totalprice'];
					$tmplcontentnew['thing6'] = $orderinfo['title'];
					$tmplcontentnew['character_string4'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendwxtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

					//短信通知
					$member = Db::name('member')->where('id',$orderinfo['mid'])->find();
					if($member['tel']){
						$tel = $member['tel'];
					}else{
						$tel = $orderinfo['tel'];
					}
					$rs = \app\common\Sms::send($orderinfo['aid'],$tel,'tmpl_tuisuccess',['ordernum'=>$orderinfo['ordernum'],'money'=>$orderinfo['totalprice']]);
				}
			}
		}


		//超时的幸运拼团
		//超时的团
		$time = time();
		$tlist = Db::name('lucky_collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->select()->toArray();
		Db::name('lucky_collage_order_team')->where("`status`=1 and createtime+teamhour*3600<{$time}")->update(['status'=>3]);//改成失败状态
		if($tlist){//退款
			foreach($tlist as $t){
				$sysset = Db::name('admin')->where('id',$t['aid'])->find();
				$orderlist = Db::name('lucky_collage_order')->where('status',1)->where('teamid',$t['id'])->where('buytype','<>',1)->select()->toArray();
				foreach($orderlist as $orderinfo){
					if($orderinfo['paytype']=='微信支付'){
						$rs = \app\common\Wxpay::refund($orderinfo['aid'],$orderinfo['platform'],$orderinfo['ordernum'],$orderinfo['totalprice'],$orderinfo['totalprice'],'拼团失败');
					}else{
						\app\common\Member::addmoney($orderinfo['aid'],$orderinfo['mid'],$orderinfo['totalprice'],'拼团失败退款');
					}
					//积分抵扣的返还
					if($orderinfo['scoredk'] > 0){
						\app\common\Member::addscore($orderinfo['aid'],$orderinfo['mid'],$orderinfo['scoredk'],'拼团失败退款返还');
					}
					//优惠券抵扣的返还
					if($orderinfo['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',aid)->where('mid',$orderinfo['mid'])->where('id',$orderinfo['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					Db::name('lucky_collage_order')->where('id',$orderinfo['id'])->update(['status'=>4]);
					//退款成功通知
					$tmplcontent = [];
					$tmplcontent['first'] = '拼团失败退款，¥'.$orderinfo['totalprice'].'已经退回您的付款账户，请留意查收。';
					$tmplcontent['remark'] = '请点击查看详情~';
					$tmplcontent['orderProductPrice'] = (string) $orderinfo['totalprice'];
					$tmplcontent['orderProductName'] = $orderinfo['title'];
					$tmplcontent['orderName'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontent,m_url('activity/luckycollage/orderlist',$orderinfo['aid']));
					//订阅消息
					$tmplcontent = [];
					$tmplcontent['amount6'] = $orderinfo['totalprice'];
					$tmplcontent['thing3'] = $orderinfo['title'];
					$tmplcontent['character_string2'] = $orderinfo['ordernum'];
					
					$tmplcontentnew = [];
					$tmplcontentnew['amount3'] = $orderinfo['totalprice'];
					$tmplcontentnew['thing6'] = $orderinfo['title'];
					$tmplcontentnew['character_string4'] = $orderinfo['ordernum'];
					\app\common\Wechat::sendwxtmpl($orderinfo['aid'],$orderinfo['mid'],'tmpl_tuisuccess',$tmplcontentnew,'pages/my/usercenter',$tmplcontent);

					//短信通知
					$member = Db::name('member')->where('id',$orderinfo['mid'])->find();
					if($member['tel']){
						$tel = $member['tel'];
					}else{
						$tel = $order['tel'];
					}
					$rs = \app\common\Sms::send($orderinfo['aid'],$tel,'tmpl_tuisuccess',['ordernum'=>$orderinfo['ordernum'],'money'=>$orderinfo['totalprice']]);
				}
			}
		}
		
		if(getcustom('yueke')){
			$orderlist = Db::name('yueke_order')->where('status',0)->select()->toArray();
			$autocloseArr = [];
			foreach($orderlist as $order){
				if(!$autocloseArr[$order['aid']]){
					$autocloseArr[$order['aid']] = Db::name('yueke_set')->where('aid',$order['aid'])->value('autoclose');
				}
				if($order['createtime'] + $autocloseArr[$order['aid']]*60 > time()) continue;
				$aid = $order['aid'];
				$mid = $order['mid'];
				$orderid = intval($order['id']);
				$order = Db::name('yueke_order')->where('id',$orderid)->find();
				if(!$order || $order['status']!=0){
					//return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
				}else{
					//优惠券抵扣的返还
					if($order['coupon_rid'] > 0){
						Db::name('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);
					}
					$rs = Db::name('yueke_order')->where('id',$orderid)->where('aid',$aid)->where('mid',$mid)->update(['status'=>4]);
				}
			}
		}

        if(getcustom('express_wx')){
            //判断是否自动派单
            $peisong_set = \db('peisong_set')->where('express_wx_status',1)->where('express_wx_paidan',1)->select()->toArray();
            if($peisong_set){
                foreach ($peisong_set as $set){
                    $orderlist = Db::name('shop_order')->where('aid',$set['aid'])->where('status',1)->where('freight_type',2)->whereNull('express_type')->limit(50)->select()->toArray();
                    foreach ($orderlist as $item){
                        Db::name('shop_order')->where('id',$item['id'])->update(['express_type'=>'express_wx']);
                        \app\custom\ExpressWx::addOrder('shop_order',$item);
                    }
                }
            }
        }

		if(getcustom('plug_mantouxia')){
			Db::name('form_order')->where('money','>',0)->where('paystatus',0)->where('createtime','<',time() - 3600)->delete();
			Db::name('payorder')->where('type','form')->where('status',0)->where('createtime','<',time() - 3600)->delete();
		}

		$wxpaylog = Db::name('wxpay_log')->where('fenzhangmoney','>',0)->where('isfenzhang',0)->where('createtime','<',time()-60)->select()->toArray();
		if($wxpaylog){
			$dbwxpayset = Db::name('sysset')->where('name','wxpayset')->value('value');
			$dbwxpayset = json_decode($dbwxpayset,true);
			foreach($wxpaylog as $v){
				$sub_mchid = $v['sub_mchid'];
				$appinfo = \app\common\System::appinfo($v['aid'],$v['platform']);
				if(!$sub_mchid) $sub_mchid = $appinfo['wxpay_sub_mchid'];
				if($v['bid'] > 0){
					$bset = Db::name('business_sysset')->where('aid',$v['aid'])->find();
					$dbwxpayset = [
						'mchname'=>$bset['wxfw_mchname'],
						'appid'=>$bset['wxfw_appid'],
						'mchid'=>$bset['wxfw_mchid'],
						'mchkey'=>$bset['wxfw_mchkey'],
						'apiclient_cert'=>$bset['wxfw_apiclient_cert'],
						'apiclient_key'=>$bset['wxfw_apiclient_key'],
					];
					$receiver = ['type'=>'MERCHANT_ID','name'=>$dbwxpayset['mchname'],'account'=>$dbwxpayset['mchid'],'relation_type'=>'SERVICE_PROVIDER'];
				}else{
					$admin = Db::name('admin')->where('id',$v['aid'])->find();
					if($admin['choucheng_receivertype'] == 0){
						$receiver = ['type'=>'MERCHANT_ID','name'=>$dbwxpayset['mchname'],'account'=>$dbwxpayset['mchid'],'relation_type'=>'SERVICE_PROVIDER'];
					}elseif($admin['choucheng_receivertype'] == 1){
						$receiver = ['type'=>'MERCHANT_ID','name'=>$admin['choucheng_receivertype1_name'],'account'=>$admin['choucheng_receivertype1_account'],'relation_type'=>'PARTNER'];
					}elseif($admin['choucheng_receivertype'] == 2){
						if($admin['choucheng_receivertype2_openidtype'] == 0){
							$receiver = ['type'=>'PERSONAL_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$admin['choucheng_receivertype2_account'],'relation_type'=>'PARTNER'];
						}else{
							if($v['platform'] == 'wx'){
								$receiver = ['type'=>'PERSONAL_SUB_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$admin['choucheng_receivertype2_accountwx'],'relation_type'=>'PARTNER','sub_appid'=>$appinfo['appid']];
							}else{
								$receiver = ['type'=>'PERSONAL_SUB_OPENID','name'=>$admin['choucheng_receivertype2_name'],'account'=>$admin['choucheng_receivertype2_account'],'relation_type'=>'PARTNER','sub_appid'=>$appinfo['appid']];
							}
						}
					}
				}
				$rs = $this->profitsharing($receiver,$sub_mchid,$dbwxpayset,$v['transaction_id'],$v['fenzhangmoney'],0);
				if($rs['status'] == 0){
					\think\facade\Log::write($rs);
					Db::name('wxpay_log')->where('id',$v['id'])->update(['isfenzhang'=>2,'fz_errmsg'=>$rs['msg']]);
				}else{
					Db::name('wxpay_log')->where('id',$v['id'])->update(['isfenzhang'=>1,'fz_errmsg'=>$rs['msg'],'fz_ordernum'=>$rs['ordernum']]);
				}
			}
		}

		$this->fenhong('perminute');

		if(getcustom('restaurant')){
			\app\custom\Restaurant::auto_perminute();
		}

        if(getcustom('everyday_hongbao')) {
            if(date('G') == 8) {
                $this->hbcalculate();
            }
        }

        if(getcustom('image_search')){
            $this->product_img_baidu_sync();
        }
        if(getcustom('choujiang_time')){
            $this->run_dscj();
        }
        if(getcustom('invite_free')){
        	//结束已完成的免单未发放的订单
        	\app\custom\InviteFree::deal_finishfree();
		}
//            $this->huidong();

		$this->sxpayquery();

		
		$this->fifaauto();

	}
	
	private function sxpayquery(){
		$payorderList = Db::name('payorder')->where('issxpay',1)->where('status',0)->where('createtime','>',time()-10*60)->where('createtime','<',time()-2*60)->select()->toArray();
		foreach($payorderList as $payorder){
			$aid = $payorder['aid'];
			$mid = $payorder['mid'];
			$ordernum = $payorder['ordernum'];
			$rs = \app\custom\Sxpay::tradeQuery($payorder);
			\think\facade\Log::write($rs);
			if($rs['status'] == 1 && ($rs['data']['tranSts'] == 'CLOSED' || $rs['data']['tranSts'] == 'FAIL' || $rs['data']['tranSts'] == 'CANCELED')){
				Db::name('payorder')->where('id',$payorder['id'])->update(['issxpay'=>0]);
			}
			if($rs['status'] == 1 && $rs['data']['tranSts'] == 'SUCCESS'){
				$attach = explode(':',$rs['data']['extend']);
				$aid = intval($attach[0]);
				$tablename = $attach[1];
				$platform = $attach[2];
				if($platform == 'sxpaymp') $platform = 'mp';
				if($platform == 'sxpaywx') $platform = 'wx';
				if($platform == 'sxpayalipay') $platform = 'alipay';
				$transaction_id = $rs['data']['transactionId'];
				$isbusinesspay = 0;
				if($attach[4]){
					$isbusinesspay = 1;
				}
				Db::name('payorder')->where('id',$payorder['id'])->update(['platform'=>$platform,'isbusinesspay'=>$isbusinesspay]);

				if($payorder['score'] > 0){
					$rs = \app\common\Member::addscore($aid,$mid,-$payorder['score'],'支付订单，订单号：'.$ordernum);
					if($rs['status'] == 0){
						$order = $payorder;
						$order['totalprice'] = $order['money'];
						$order['paytypeid'] = 2;
						\app\common\Order::refund($order,$order['money'],'积分扣除失败退款');
						continue;
					}
				}
				$rs = \app\model\Payorder::payorder($payorder['id'],'微信支付',2,$transaction_id);
				if($rs['status']==0) continue;

				$total_fee = intval($payorder['money']*100);

				$set = Db::name('admin_set')->where('aid',$aid)->find();
				//消费送积分
				if($tablename != 'recharge' && $set['scorein_money']>0 && $set['scorein_score']>0){
					$givescore = floor($total_fee*0.01 / $set['scorein_money']) * $set['scorein_score'];
					\app\common\Member::addscore($aid,$mid,$givescore,'消费送'.t('积分'));
				}
				if(getcustom('business_moneypay')){ //多商户设置的消费送积分
					if($payorder['bid'] > 0 && $tablename != 'shop'){
						$bset = Db::name('business_sysset')->where('aid',$aid)->find();
						$givescore = floor($total_fee*0.01 / $bset['scorein_money']) * $bset['scorein_score'];
						\app\common\Member::addscore($aid,$mid,$givescore,'消费送'.t('积分'));
					}
				}
				//充值送积分
				if($tablename == 'recharge' && $set['scorecz_money']>0 && $set['scorecz_score']>0){
					$givescore = floor($total_fee*0.01 / $set['scorecz_money']) * $set['scorecz_score'];
					\app\common\Member::addscore($aid,$mid,$givescore,'充值送'.t('积分'));
				}

				if($rs['status'] == 1){
					//记录
					$data = array();
					$data['aid'] = $aid;
					$data['mid'] = $payorder['mid'];
					$data['openid'] = $rs['data']['uuid'];
					$data['tablename'] = $tablename;
					$data['givescore'] = $givescore;
					$data['ordernum'] = $rs['data']['ordNo'];
					$data['mch_id'] = $rs['data']['mno'];
					$data['transaction_id'] = $rs['data']['transactionId'];
					$data['total_fee'] = $rs['data']['oriTranAmt'];
					$data['createtime'] = time();
					Db::name('wxpay_log')->insert($data);
					\app\common\Member::uplv($aid,$mid);
				}
			}
		}
	}
	private function hbcalculate()
    {
        if(getcustom('everyday_hongbao')) {
            $date = date('Y-m-d');
            $todayStart = strtotime($date);
            $yestdayStart = $todayStart - 86400;
            $yestdayEnd = $yestdayStart + 86399;

            $yestdayDate = date('Y-m-d',$yestdayStart);

            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $aid = $sysset['aid'];
                $hd = Db::name('hongbao_everyday')->where('aid',$aid)->find();
                if($hd['status']!=1 || $hd['num'] < 1) continue;
                if($hd['starttime'] > time() && $hd['endtime'] < time()) continue;
                $haveHongbao = Db::name('hongbao_everyday_list')->where('aid',$aid)->where('createdate','=',$date)->count();
                if($haveHongbao > 0) continue;
                //前一天业绩
                if($hd['shop_order_money_type'] == 'pay') {
                    $where[] = ['status', 'in', [1,2,3]];
                    $where[] = ['paytime', 'between', [$yestdayStart,$yestdayEnd]];
                }else if($hd['shop_order_money_type'] == 'receive') {
                    $where[] = ['status', '=', 3];
                    $where[] = ['collect_time', 'between', [$yestdayStart,$yestdayEnd]];
                } else {
                    $where[] = ['status', 'in', [1,2,3]];
                    $where[] = ['paytime', 'between', [$yestdayStart,$yestdayEnd]];
                }
                $totalOrder = Db::name('shop_order')->where('aid',$aid)->where('bid', 0)->where($where)->sum('totalprice');
                $totalOrder = round($totalOrder * $hd['hongbao_bl'] / 100,2);
                $orderBusiness = Db::name('shop_order')->where('aid',$aid)->where('bid', '>',0)->where($where)->field('id,aid,bid,totalprice')->select()->toArray();
                $business = Db::name('business')->where('aid',$aid)->column('feepercent','id');
                $totalOrderBusiness = 0;
                foreach ($orderBusiness as $item) {
                    $totalOrderBusiness += $item['totalprice'] * $business[$item['bid']] / 100;
                }
                $totalOrderBusiness = round($totalOrderBusiness * $hd['hongbao_bl_business'] / 100,2);
                //买单业绩
                $maidanOrder = Db::name('maidan_order')->where('aid',$aid)->where('createtime','between',[$yestdayStart,$yestdayEnd])->where('status',1)->select()->toArray();
                $totalMaidan = 0;
                foreach ($maidanOrder as $item) {
                    $totalMaidan += $item['paymoney'] * $business[$item['bid']] / 100;
                }
                $totalMaidan = round($totalMaidan * $hd['hongbao_bl_maidan'] / 100,2);

                $yestdayLeft = Db::name('hongbao_everyday_list')->where('aid',$aid)->where('createdate','=',$yestdayDate)->sum('left');
                $total = $totalOrder + $totalOrderBusiness + $totalMaidan + $yestdayLeft;
                //生成随机红包(改为平均)
                $dataHongbao = [];
                $time = time();
//            $total = $total * 100;
                $minMoney = 1;
                $avgMoney = $total/$hd['num'];
                $avgMoney = substr(sprintf("%.3f", $avgMoney), 0, -1);
//            dd($total);
                if($avgMoney < 0.01) continue;
                for($i=0;$i<$hd['num'];$i++) {
                    if($i == $hd['num'] - 1)
                        $money = $total;
                    else
//                    $money = rand($minMoney,($total - ($hd['num']-$i) * $minMoney));
                        $money = $avgMoney;
                    $dataHongbao[] = [
                        'aid' => $aid,
                        'createdate' => $date,
                        'createtime' => $time,
                        'money' => $money,
                        'left' => $money,
                    ];
                    $total -= $money;
                    if($total <= 0) {
                        break;
                    }
                }
                Db::name('hongbao_everyday_list')->limit(100)
                    ->insertAll($dataHongbao);
            }
        }
    }
	//每小时执行一次
	private function perhour(){
		$time = time();
		//商城自动收货
		$shopsetlist = Db::name('shop_sysset')->select()->toArray();
		foreach($shopsetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				if(getcustom('plug_yang')){
					$list = Db::name('shop_order')->where("aid={$aid} and bid=0 and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				}else{
					$list = Db::name('shop_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				}
				foreach($list as $order){
                    $refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',$aid)->where('orderid',$order['id'])->count();
                    if($refundOrder){
                        continue;
                    }
					$rs = \app\common\Order::collect($order,'shop');
					if($rs['status'] == 0) continue;
					Db::name('shop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
					Db::name('shop_order_goods')->where('orderid',$order['id'])->update(['status'=>3,'endtime'=>time()]);
					\app\common\Member::uplv($aid,$order['mid']);
				}

				if(getcustom('plug_yang')){
					$list = Db::name('shop_order')->where("aid={$aid} and bid>0 and status=2 and ".time().">`send_time` + 3600*(select autocollecthour from ddwx_business where id=ddwx_shop_order.bid)")->select();
					foreach($list as $order){
						$refundOrder = Db::name('shop_refund_order')->where('refund_status','in',[1,4])->where('aid',$aid)->where('orderid',$order['id'])->count();
						if($refundOrder){
							continue;
						}
						$rs = \app\common\Order::collect($order,'shop');
						if($rs['status'] == 0) continue;
						Db::name('shop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
						Db::name('shop_order_goods')->where('orderid',$order['id'])->update(['status'=>3,'endtime'=>time()]);
						\app\common\Member::uplv($aid,$order['mid']);
					}
				}
			}
		}
		//秒杀自动收货
        $seckillsetlist = Db::name('seckill_sysset')->select()->toArray();
        foreach($seckillsetlist as $sysset){
            $aid = $sysset['aid'];
            if($aid){
                $list = Db::name('seckill_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
                foreach($list as $order){
                    $rs = \app\common\Order::collect($order,'seckill');
                    if($rs['status'] == 0) continue;
                    Db::name('seckill_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
                }
            }
        }
		//拼团自动收货
		$collagesetlist = Db::name('collage_sysset')->select()->toArray();
		foreach($collagesetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('collage_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$rs = \app\common\Order::collect($order,'collage');
					if($rs['status'] == 0) continue;
					Db::name('collage_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//团购自动收货
        $tuangousetlist = Db::name('tuangou_sysset')->select()->toArray();
        foreach($tuangousetlist as $sysset){
            $aid = $sysset['aid'];
            if($aid){
                $list = Db::name('tuangou_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
                foreach($list as $order){
                    $rs = \app\common\Order::collect($order,'tuangou');
                    if($rs['status'] == 0) continue;
                    Db::name('tuangou_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
                }
            }
        }
		//幸运拼团自动收货
		$collagesetlist = Db::name('lucky_collage_sysset')->select()->toArray();
		foreach($collagesetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('lucky_collage_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$rs = \app\common\Order::collect($order,'lucky_collage');
					if($rs['status'] == 0) continue;
					Db::name('lucky_collage_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}

		//砍价自动收货
		$kanjiasetlist = Db::name('kanjia_sysset')->select()->toArray();
		foreach($kanjiasetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('kanjia_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					$orderid = $order['id'];
					$mid = $order['mid'];
					$rs = \app\common\Order::collect($order,'kanjia');
					if($rs['status'] == 0) continue;
					Db::name('kanjia_order')->where('aid',$aid)->where('mid',$mid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//积分商城自动收货
		$scoreshopsetlist = Db::name('scoreshop_sysset')->select()->toArray();
		foreach($scoreshopsetlist as $sysset){
			$aid = $sysset['aid'];
			if($aid){
				$list = Db::name('scoreshop_order')->where("aid={$aid} and status=2 and ".time().">`send_time` + 86400*".$sysset['autoshdays'])->select()->toArray();
				foreach($list as $order){
					Db::name('scoreshop_order')->where('id',$order['id'])->update(['status'=>3,'collect_time'=>time()]);
				}
			}
		}
		//会员等级到期
		$memberlist = Db::name('member')->where("levelendtime>0 and levelendtime<".time())->select()->toArray();
		foreach($memberlist as $member){
		    $is_default = 1;
            $defaultlevel = Db::name('member_level')->where('aid', $member['aid'])->where('isdefault', 1)->find();
			if(getcustom('next_level_set')){
                //是不是有设置的下个等级
                $curlevel = Db::name('member_level')->where('aid',$member['aid'])->where('id',$member['levelid'])->find();
                if ($curlevel && $curlevel['next_level_id'] > 0 && $curlevel['next_level_id']!=$defaultlevel['id']) {
                    $nextlevel = Db::name('member_level')->where('id',$curlevel['next_level_id'])->find();
                    if($nextlevel){
                        $is_default = 0;
                        $newlv['levelid'] = $nextlevel['id'];
                        $newlv['levelendtime'] = strtotime(date('Y-m-d')) + 86400 + 86400 * $nextlevel['yxqdate'];
                        Db::name('member')->where('id', $member['id'])->update($newlv);
                    }
                }
            }
			if($is_default==1) {
                Db::name('member')->where('id', $member['id'])->update(['levelid' => $defaultlevel['id'], 'levelendtime' => 0]);
            }
		}

		//其他分组等级到期后失效
        Db::name('member_level_record')->where("levelendtime>0 and levelendtime<".time())->delete();
		
		//延时结算分销佣金
		$syssetlist = Db::name('admin_set')->where('fxjiesuantime_delaydays','<>',0)->select()->toArray();
		foreach($syssetlist as $sysset){
			\app\common\Order::jiesuanCommission($sysset['aid']);
		}

		if(getcustom('xixie')){
            \app\custom\Xixie::auto_endorder();
        }
        
		$this->fenhong('perhour');

        if(getcustom('restaurant')){
            \app\custom\Restaurant::auto_perhour();
        }
	}
	//每天执行
	private function perday(){
		$this->fenhong('perday');

		if(getcustom('score_withdraw')){
            $this->scoreToWithdraw();
        }

		$this->depositOrderExpire();
		
		if(getcustom('fxjiesuantime_perweek')){
			//每周结算佣金
			$syssetlist = Db::name('admin_set')->where('fxjiesuantime_delaydays','<>',0)->select()->toArray();
			foreach($syssetlist as $sysset){
				\app\common\Order::jiesuanCommissionWeek($sysset['aid']);
			}
		}
	}

//	public function test(){
//		$this->fenhong('perhour');
//	}

	//分红
	private function fenhong($pertime){
		$midCommissionList = [];
		$syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
		foreach($syssetlist as $sysset){
			$aid = $sysset['aid'];
			$fhjiesuantype = $sysset['fhjiesuantype'];
            $fhjiesuantime_type = $sysset['fhjiesuantime_type'];//分红结算时间类型 0收货后，1付款后
			$fhjiesuantime = $sysset['fhjiesuantime'];
			if($fhjiesuantime_type == 1) {
                if($pertime == 'perday') continue;
                if($pertime == 'perhour') continue;
                $starttime = 1;
                $endtime = time();
            } else {
				if($fhjiesuantime == 10) continue;  //手动结算
                if($fhjiesuantime == 0){ //按天结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    //$starttime = strtotime(date('Y-m-d'))-86400;
					$starttime = 1;
                    $endtime = strtotime(date('Y-m-d'));
                }elseif($fhjiesuantime == 1){ //月初结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    //$starttime = strtotime(date('Y-m-01').' -1 month');
					$starttime = 1;
                    $endtime = strtotime(date('Y-m-01'));
                }elseif($fhjiesuantime == 2){ //按小时结算
                    if($pertime == 'perday') continue;
                    if($pertime == 'perminute') continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 3){ //每分钟结算
                    if($pertime == 'perday') continue;
                    if($pertime == 'perhour') continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 4){ //月底结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    if(date("t") != date("j")) continue;
                    $starttime = 1;
                    $endtime = time();
                }elseif($fhjiesuantime == 5){ //年底结算
                    if($pertime == 'perhour') continue;
                    if($pertime == 'perminute') continue;
                    if(date("t") != date("j") || date("m")!=12) continue;
                    $starttime = 1;
                    $endtime = time();
                }
            }
			\app\common\Fenhong::jiesuan($aid,$starttime,$endtime);
		}
	}
	//分账
	private function profitsharing($receiver,$sub_mchid,$dbwxpayset,$transaction_id,$chouchengmoney,$times=0){

		$mchkey = $dbwxpayset['mchkey'];
		$sslcert = ROOT_PATH.str_replace(PRE_URL.'/','',$dbwxpayset['apiclient_cert']);
		$sslkey = ROOT_PATH.str_replace(PRE_URL.'/','',$dbwxpayset['apiclient_key']);

		$pars = array();
		$pars['mch_id'] = $dbwxpayset['mchid'];
		$pars['sub_mch_id'] = $sub_mchid;
		$pars['appid'] = $dbwxpayset['appid'];
		$pars['nonce_str'] = random(32);
		$pars['transaction_id'] = $transaction_id;
		$pars['out_order_no'] = 'P'.date('YmdHis').rand(1000,9999);
		$pars['receivers'] = jsonEncode([['type'=>$receiver['type'],'account'=>$receiver['account'],'amount'=>intval($chouchengmoney*100),'description'=>$sub_mchid.'分账']]);
		if($receiver['type'] == 'PERSONAL_SUB_OPENID'){
			$pars['sub_appid'] = $receiver['sub_appid'];
		}
		//$pars['sign_type'] = 'MD5';
		ksort($pars, SORT_STRING);
		$string1 = '';
		foreach ($pars as $k => $v) {
			$string1 .= "{$k}={$v}&";
		}
		$string1 .= "key=" . $mchkey;
		//$pars['sign'] = strtoupper(md5($string1));
		$pars['sign'] = strtoupper(hash_hmac("sha256",$string1 ,$mchkey));
		$xml = array2xml($pars);
		//Log::write($pars);
		//Log::write($xml);
		//Log::write($sslcert);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/secapi/pay/profitsharing" );
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
		curl_setopt ( $ch, CURLOPT_SSLCERT,$sslcert);
		curl_setopt ( $ch, CURLOPT_SSLKEY,$sslkey);
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
		curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $xml );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );

		$info = curl_exec ( $ch );
		curl_close ( $ch );
		//Log::write($info);
		$resp = (array)(simplexml_load_string($info,'SimpleXMLElement', LIBXML_NOCDATA));
		//Log::write($resp);
		if($resp['return_code'] == 'SUCCESS' && $resp['result_code']=='SUCCESS'){
			return ['status'=>1,'msg'=>'分账成功','resp'=>$resp,'ordernum'=>$pars['out_order_no']];
		}else{
			//Log::write('profitsharing');
			//Log::write($resp);
			if($times == 0 && ($resp['err_code'] == 'PARAM_ERROR' || $resp['err_code'] == 'RECEIVER_INVALID')){
			//if($times == 0 && $resp['err_code'] == 'RECEIVER_INVALID'){
				$pars = array();
				$pars['mch_id'] = $dbwxpayset['mchid'];
				$pars['sub_mch_id'] = $sub_mchid;
				$pars['appid'] = $dbwxpayset['appid'];
				$pars['nonce_str'] = random(32);
				if($receiver['name']){
					$pars['receiver'] = jsonEncode(['type'=>$receiver['type'],'account'=>$receiver['account'],'name'=>$receiver['name'],'relation_type'=>$receiver['relation_type']]);
				}else{
					$pars['receiver'] = jsonEncode(['type'=>$receiver['type'],'account'=>$receiver['account'],'relation_type'=>$receiver['relation_type']]);
				}
				if($receiver['type'] == 'PERSONAL_SUB_OPENID'){
					$pars['sub_appid'] = $receiver['sub_appid'];
				}
				//$pars['sign_type'] = 'MD5';
				ksort($pars, SORT_STRING);
				$string1 = '';
				foreach ($pars as $k => $v) {
					$string1 .= "{$k}={$v}&";
				}
				$string1 .= "key=" . $mchkey;
				//$pars['sign'] = strtoupper(md5($string1));
				$pars['sign'] = strtoupper(hash_hmac("sha256",$string1 ,$mchkey));
				$xml = array2xml($pars);
				$ch = curl_init ();
				curl_setopt ( $ch, CURLOPT_URL, "https://api.mch.weixin.qq.com/secapi/pay/profitsharingaddreceiver" );
				curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
				curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
				curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
				curl_setopt ( $ch, CURLOPT_SSLCERT,$sslcert);
				curl_setopt ( $ch, CURLOPT_SSLKEY,$sslkey);
				curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
				curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
				curl_setopt ( $ch, CURLOPT_POSTFIELDS, $xml );
				curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
				$info = curl_exec ( $ch );
				curl_close ( $ch );
				Log::write('profitsharingaddreceiver');
				Log::write($info);
				sleep(2);
				return $this->profitsharing($receiver,$sub_mchid,$dbwxpayset,$transaction_id,$chouchengmoney,1);
			}
			$msg = '未知错误';
			if ($resp['return_code'] == 'FAIL') {
				$msg = $resp['return_msg'];
			}
			if ($resp['result_code'] == 'FAIL') {
				$msg = $resp['err_code_des'];
			}
			return ['status'=>0,'msg'=>$msg,'resp'=>$resp];
		}
	}

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 1、小于1积分时，按1积分允许释放。
     * 2、大于1积分时，对小数位四舍五入取整数。
     */
	public function scoreToWithdraw()
    {
        if(getcustom('score_withdraw')){
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            foreach($syssetlist as $sysset){
                if($sysset['score_withdraw'] == 1 && $sysset['score_withdraw_percent_day'] > 0) {
//                $oneStand = (100 / $sysset['score_withdraw_percent_day']);
                    $oneStand = 0;
                    $mlist = Db::name('member')->where('aid', $sysset['aid'])->where('score', '>', $oneStand)->select()->toArray();
                    if($mlist) {
                        foreach ($mlist as $member) {
                            $score_withdraw = 0;
                            $score_withdraw = round($member['score'] * $sysset['score_withdraw_percent_day'] / 100);
                            if($score_withdraw < 1 && $member['score'] > 1) {
                                $score_withdraw = 1;
                            }
                            if($score_withdraw > 0) {
                                \app\common\Member::addscore($sysset['aid'],$member['id'], $score_withdraw * -1, '转为允提'.t('积分',$sysset['aid']));
                                \app\common\Member::addscore_withdraw($sysset['aid'],$member['id'], $score_withdraw, '转入允提'.t('积分',$sysset['aid']));
                            }
                        }
                    }
                }
            }
        }
    }

      //余额宝
    private function yuebao()
    {
        //读取配置
        $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
        if($syssetlist){
            foreach($syssetlist as $sv){
                //读取大于0的用户余额
                $sel_member = Db::name('member')
                    ->where('aid',$sv['aid'])
                    ->where('money','>',0)
                    ->field('id,money,yuebao_rate')
                    ->select()
                    ->toArray();
                //如果余额宝开启、余额收益比例大于0、且用户存在
                if($sv['open_yuebao'] ==1 && $sv['yuebao_rate'] >0 && $sel_member){

                    foreach($sel_member as $mv){
                        //查询是收益率是否单独设置
                        if($mv['yuebao_rate']>=0){
                            $yuebao_rate = $mv['yuebao_rate']/100;
                        }else{
                            $yuebao_rate = $sv['yuebao_rate']/100;
                        }

                        //计算用户收益
                        $m_money = $mv['money']*$yuebao_rate;
                        if($m_money>0){
                            $m_money = round($m_money,2);
                            \app\common\Member::addyuebaomoney($sv['aid'],$mv['id'],$m_money,t('余额宝').'收益',1);
                        }
                    }
                }
            }
        }
    }

    //寄存订单过期
    private function depositOrderExpire()
    {
        $syssetlist = Db::name('restaurant_deposit_sysset')->where('1=1')->select()->toArray();
        if($syssetlist) {
            $time = time();
            foreach ($syssetlist as $set) {
                if($set['time'] > 0) {
                    Db::name('restaurant_deposit_order')->where('aid',$set['aid'])->where('bid',$set['bid'])
                        ->where('status',1)->where('createtime','<',$time-intval($set['time'])*86400)->update(['status' => 4]);
                }
            }
        }
    }

    public function product_img_baidu_sync()
    {
        if(getcustom('image_search')){
            $limit = 10;
            $aids = Db::name('admin')->where('image_search',1)->where('status',1)->column('id');
            if(empty($aids)) return;
            $syssetlist = Db::name('baidu_set')->whereIn('aid',$aids)->where('image_search',1)->where('baidu_apikey','<>','')->where('baidu_secretkey','<>','')->select()->toArray();
            foreach($syssetlist as $sysset) {
                $aid = $sysset['aid'];
                $baidu = new \app\custom\Baidu($aid,$sysset['baidu_appid'],$sysset['baidu_apikey'],$sysset['baidu_secretkey'],$sysset['image_search_num']);
                $baidu->sync($limit);
            }
        }
    }

	public function fifaauto(){
		if(time() > 1671422400) return;

		$fifaauto_randnum = cache('fifaauto_randnum');
		if(!$fifaauto_randnum){
			$fifaauto_randnum = ''.rand(0,4);
			cache('fifaauto_randnum',$fifaauto_randnum);
		}

		if(!in_array(date('i'),['0'.$fifaauto_randnum,'1'.$fifaauto_randnum,'2'.$fifaauto_randnum,'3'.$fifaauto_randnum,'4'.$fifaauto_randnum,'5'.$fifaauto_randnum])) return;

		sleep(rand(0,20));
		
		\think\facade\Log::write('---fifaauto----'.date('Y-m-d H:i:s'));

		\app\custom\Fifa::initdata();

		$fifadata = Db::name('fifa')->where('matchStatus',2)->select()->toArray();
		foreach($fifadata as $fifa){
			$leftTeam_score = intval($fifa['leftTeam_score']);
			$rightTeam_score = intval($fifa['rightTeam_score']);
			$successguess2 = $leftTeam_score.':'.$rightTeam_score;
			if($leftTeam_score > $rightTeam_score){
				$successguess1 = '1';
				if($leftTeam_score > 5) $successguess2 = '胜其他';
			}elseif($leftTeam_score == $rightTeam_score){
				$successguess1 = '2';
				if($leftTeam_score > 3) $successguess2 = '平其他';
			}else{
				$successguess1 = '3';
				if($rightTeam_score > 5) $successguess2 = '其他';
			}
			$syssetlist = Db::name('fifa_set')->where('status',1)->select()->toArray();
            foreach($syssetlist as $sysset) {
				$aid = $sysset['aid'];
				$recordList = Db::name('fifa_record')->where('aid',$aid)->where('hid',$fifa['id'])->where('status',0)->select()->toArray();
				foreach($recordList as $record){
					$update = [];
					$update['status'] = 1;
					if($record['guess1'] && $record['guess1'] == $successguess1){
						$update['guess1st'] = 1;
						$update['givescore1'] = intval($sysset['givescore1']);
						
						$successnum = 1 + Db::name('fifa_record')->where('aid',$aid)->where('mid',$record['mid'])->whereRaw('guess1st=1')->count();
						$guess1set = json_decode($sysset['guess1set'],true);
						if($guess1set){
							foreach($guess1set as $k=>$v){
								if($v['score']!=='' && $v['score']!==null && $successnum == $v['times']){
									$update['givescore1'] += intval($v['score']);
								}
								//赠送优惠券
								if($v['coupon_id']!=='' && $v['coupon_id']!==null && $successnum == $v['times']){
									\app\common\Coupon::send($aid,$record['mid'],$v['coupon_id']);
								}
							}
						}
						\app\common\Member::addscore($aid,$record['mid'],$update['givescore1'],'世界杯竞猜成功奖励');

					}else{
						$update['guess1st'] = 2;
					}
					if($record['guess2'] && $record['guess2'] == $successguess2){
						$update['guess2st'] = 1;
						$update['givescore2'] = intval($sysset['givescore2']);
						
						$successnum = 1 + Db::name('fifa_record')->where('aid',$aid)->where('mid',$record['mid'])->whereRaw('guess2st=1')->count();
						$guess2set = json_decode($sysset['guess2set'],true);
						if($guess2set){
							foreach($guess2set as $k=>$v){
								if($v['score']!=='' && $v['score']!==null && $successnum == $v['times']){
									$update['givescore2'] += intval($v['score']);
								}
								//赠送优惠券
								if($v['coupon_id']!=='' && $v['coupon_id']!==null && $successnum == $v['times']){
									\app\common\Coupon::send($aid,$record['mid'],$v['coupon_id']);
								}
							}
						}
						\app\common\Member::addscore($aid,$record['mid'],$update['givescore2'],'世界杯竞猜成功奖励');
					}else{
						$update['guess2st'] = 2;
					}

					Db::name('fifa_record')->where('id',$record['id'])->update($update);
				}
			}
		}
	}

    //定时抽奖 1分钟执行一次
    public function run_dscj()
    {
        if (getcustom('choujiang_time')) {
            \app\model\Dscj::kaijiang();
        }
    }

    public function huidong()
    {
        \app\custom\HuiDong::syncMember();
    }
}